/**
 * Created by zhulizhe on 2017/8/29.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    DeviceEventEmitter,
    ScrollView,
    StyleSheet
} from 'react-native';
import Constant from '../Contant'
import {observable, action, computed, observe} from 'mobx'
import {observer} from 'mobx-react/native'
import SearchBox from "../component/SearchBox";
import {historySearchStore} from '../store/HistorySearchStore' ;
import {SectionHeader} from './DeliveryAddress' ;
import Ionicons from "react-native-vector-icons/Ionicons";
import addressMgrStore from '../store/AddrMgrStore'
import { NavigationActions } from 'react-navigation'

const resetAction = NavigationActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({ routeName: 'Root'})
    ]
})

const Item = ({name,action})=>{
    return <TouchableOpacity
        onPress={()=>{
            action() ;
        }}
        activeOpacity={0.9}
        style={[{padding:15,backgroundColor:'#fff'},styles.borderBottom]}>
        <Text>{name}</Text>
    </TouchableOpacity>
}

// 头部搜索组件
const Header = ({textChange,navigation})=>{
    return <View style={{flexDirection:'row',paddingHorizontal:10,alignItems:'center',backgroundColor:'#fff',paddingVertical:10}}>
        <TouchableOpacity
            activeOpacity={0.9}
            onPress={()=>{
                navigation.goBack();
            }}
            style={{flex:1,flexDirection:'row',alignItems:'center'}}>
            <Ionicons name="ios-arrow-back-outline" color={Constant.TEXT_COLOR_6} size={30}/>
            <Text style={{paddingHorizontal:5,fontSize:13,color:Constant.TEXT_COLOR_6}}>取消</Text>
        </TouchableOpacity>
        <View style={{flex:6}}>
            <SearchBox
                textChange={textChange}
                //tintColor={Constant.TEXT_COLOR_D7}
                placeholder="请输入收货地址"/>
        </View>
    </View>
}

// 历史搜索展示组件
const HistoryWords = observer(({keywords=[]})=>{
    if(addressMgrStore.mapAuto.addrListByKeyword.length > 0)return null ;
    return <View>
        <SectionHeader title="历史搜索"/>
        {
            keywords.map((word,index)=>{
                return <Item
                    action={()=>{
                        // 关键词搜索
                        addressMgrStore.mapAuto.searchByWord(word.history);
                    }}
                    key={index}
                    name={word.history}/>
            })
        }
    </View>
})

// 地址列表显示组件
const AddressList = observer(({navigation})=>{
    return <View>
        {
            addressMgrStore.mapAuto.addrListByKeyword.map((poi,index)=>{
                return <Item
                    action={()=>{
                        //更新选择位置，关联地图更新
                        LOG('SearchAddress----------'+JSON.stringify(poi));
                        let addrM = addressMgrStore.mapAuto.convertPOI2Address(poi);
                        addressMgrStore.setSelected(addrM)
                        addressMgrStore.mapAuto.setMapRegion(addrM);
                        // 通知更新地图位置
                        DeviceEventEmitter.emit(Constant.CURRENTLOCATIONCHANGE,poi);
                        // 返回
                        {/*const resetAction = NavigationActions.reset({*/}
                            {/*index: 0,*/}
                            {/*actions: [*/}
                                {/*NavigationActions.navigate({ routeName: 'Root'})*/}
                            {/*]*/}
                        {/*});*/}
                        {/*navigation.dispatch(resetAction);*/}
                        navigation.goBack();
                    }}
                    key={index}
                    name={poi.name}/>
            })
        }
    </View>
})

@observer
export default class SearchAddress extends Component{

    @observable keywords = [] ;

    @observable tempWords = [] ;

    static navigationOptions = ({ navigation}) => ({
        header:null
    });

    componentDidMount() {
        // 加载历史搜索
        historySearchStore.loadHistory().then(resp => {
            if(resp){
                this.keywords = resp ;
            }
        });
    }


    // 暂存搜索历史
    saveSearchHistory(text){
        this.tempWords.push(text) ;
    }

    componentWillUnmount(){
        // 记录历史搜索文本
        historySearchStore.addKeyword(this.tempWords) ;
    }

    render(){
        return <View style={{flex:1,backgroundColor:Constant.GRAYBGCOLOR}}>
            <Header
                navigation={this.props.navigation}
                textChange={(text)=>{
                    //关键词搜索
                    addressMgrStore.mapAuto.searchByWord(text) ;
                    // 暂存关键词
                    this.saveSearchHistory(text);
                }}/>
            <ScrollView>
                <HistoryWords keywords={this.keywords}/>
                <AddressList navigation={this.props.navigation}/>
            </ScrollView>
        </View>
    }
}

const styles = {
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth
    }
}
